// data/repository/SplashRepository.kt
package com.example.bilibili_fake.data.repository

import com.example.bilibili_fake.data.model.SplashItem
import com.example.bilibili_fake.data.model.SplashResponse
import com.example.bilibili_fake.data.network.ApiClient
import com.example.bilibili_fake.data.network.SplashApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.security.MessageDigest
import android.util.Base64
import kotlin.collections.filterIsInstance

class SplashRepository {
    private val apiService: SplashApi = ApiClient.apiService

    suspend fun fetchSplashImages(): Result<List<SplashItem>> {
        return try {
            val ts = System.currentTimeMillis()
            val response = apiService.getSplashList(
                appkey = "1d8b6e7d45233436", // 替换为真实 appkey
                ts = ts,
                sign = generateSign(ts) // 传递 ts 保证一致性
            )
            if (response.isSuccessful && response.body()?.code == 0) {
                // 修复点：安全转换 data 类型
                val responseBody = response.body()
                val data: List<SplashItem> = (responseBody?.data as? List<*>)?.filterIsInstance<SplashItem>() ?: emptyList()
                Result.success(data)
            } else {
                Result.failure(Exception("Failed to load splash images"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }


    private fun generateSign(ts: Long): String {
        val secret = "560c52ccd288fed045859ed18bffd973"
        val appkey = "1d8b6e7d45233436"
        val str = "appkey=$appkey&ts=$ts$secret"
        return md5(str)
    }

    private fun md5(input: String): String {
        val digest = MessageDigest.getInstance("MD5")
        val hash = digest.digest(input.toByteArray())
        return Base64.encodeToString(hash, Base64.NO_WRAP)
    }
}
